﻿
using System;
using System.Collections.Generic;
using System.Linq;
using nanoCMS.Core.Concrete;
using nanoCMS.Core.Extensions;

namespace nanoCMS.Core.Providers
{
	public class MessageProvider
	{
		private readonly Entities entities;
		private ModuleProvider moduleProvider;
		private ModuleProvider ModuleProvider
		{
			get { return moduleProvider ?? (moduleProvider = new ModuleProvider(entities)); }
		}
		public MessageProvider(Entities entities)
		{
			this.entities = entities;
		}

		#region Add
		public Message Add(int moduleID, string key, string subject, string content, string comment, string tokenList, int? tenantId = null, int? languageId = null)
		{
			Message message = new Message
							  {
								  Key = key,
								  Subject = subject,
								  Content = content,
								  Comment = comment,
								  TokenList = tokenList,
								  LangID = languageId.IfNullSet(1),
								  TenantID = tenantId.IfNullSet(1),
								  ModuleID = moduleID
							  };
			entities.Messages.AddObject(message);
			entities.SaveChanges();
			return message;
		}

		public Message Add(string moduleName, string key, string content, int tenantID = 1, int languageId = 1)
		{
			Module module = ModuleProvider.GetModule(moduleName);
			if (module == null) throw new ArgumentException("There is no module with name:" + moduleName);

			return Add(module.ModuleID, key, string.Empty, content, string.Empty, string.Empty, tenantID, languageId);
		}
		#endregion

		#region Get
		public Message Get(string moduleName, string key, int tenantID = 1, int langID = 1)
		{
			Module module = ModuleProvider.GetModule(moduleName);
			if (module == null) throw new ArgumentException("There is no module with name:" + moduleName);
			Message message = entities.Messages.SingleOrDefault(x=>x.ModuleID == module.ModuleID && x.Key == key && x.TenantID == tenantID && x.LangID == langID);
			if (message == null) throw new Exception();
			return message;
		}

		public Message GetProcessedMessage(string moduleName, string key, Dictionary<string, string> values, int tenantID = 1, int langID = 1)
		{
			
			Message message = Get(moduleName, key, tenantID, langID);
			string token;
			foreach (var value in values)
			{
				token = "{$" + value.Key + "$}";
				if (message.Subject != null)
					message.Subject = message.Subject.Replace(token, value.Value);
				message.Content = message.Content.Replace(token, value.Value);
			}
			return message;
		}
		#endregion

		#region Edit
		//TODO: edit, delete & stuff
		#endregion
	}
}
